package com.yunao.web.thread;

import com.alibaba.fastjson.JSONObject;
import com.yunao.commons.enums.NeedAlarmEnum;
import com.yunao.commons.serachcore.core.bean.Article;
import com.yunao.commons.vo.ResultVO;
import com.yunao.entity.AloneReport;
import com.yunao.entity.ArticleItem;
import com.yunao.entity.Subject;
import com.yunao.entity.User;
import com.yunao.service.*;
import com.yunao.service.report.DateUtil;
import com.yunao.service.report.esou.ReportThread2;
import com.yunao.web.config.WxConfig;
import com.yunao.web.utils.TokenUtil;
import com.yunao.web.utils.WechatUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.boot.jaxb.hbm.spi.SubEntityInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@EnableScheduling
@Component
public class AlarmWechatThread {

    private static Logger logger = LoggerFactory.getLogger(AutoReportThread.class);

    @Autowired
    private ArticleService articleService;

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private UserService userService;

    @Autowired
    private WxConfig wxConfig;

    private int MaxThread = 15;//最大线程数


    @Scheduled(cron ="0 0/10 * * * ? ")
    public void run(){
        logger.info("发送微信预警...");
        // 所有需要使用预警的专题
        List<Subject> results = new ArrayList<>();
        List<Subject> subjects = subjectService.findByNeedAlarm(NeedAlarmEnum.NEED_ALARM.getCode());
        List<ArticleItem> articles = new ArrayList<>();
        for (Subject subject : subjects) {
            if (subject.getAlarmMethod().contains("3")){
                String openid = userService.findOne(subject.getUserId()).getOpenid();
                if (!StringUtils.isEmpty(openid)){
                    results.add(subject);
                }
            }
        }

        // 预警专题数
        int total = results.size();
        // 线程池
        ExecutorService pool = Executors.newCachedThreadPool();

        int len=MaxThread;
        int avg=total/len;
        if(avg==0)
        {
            len=total;
            avg=1;
        }
        for (int i = 0; i < len; i++) {
            int fromIndex = i * avg;
            int toIndex = i == len - 1 ? total : fromIndex + avg;
            pool.execute(new AriticleTread(results.subList(fromIndex, toIndex),userService,articleService,wxConfig));
        }
        //线程池关闭
        pool.shutdown();
    }


}
